package com.gaoyi.crm.util;

import android.os.Build;
import android.util.Base64;

import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Cipher;

public class RSAUtil {

    private final static String RSA_ALGORITHM = "RSA/ECB/PKCS1Padding";
    private static final String RSA = "RSA";
    private static final int KEY_SIZE = 1024;

//    public static Map<Integer,String> getKey(){
//        Map<Integer,String> keyMap = new HashMap<>();
//        try {
//            KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(RSA);
//            keyPairGen.initialize(KEY_SIZE,new SecureRandom());
//            KeyPair keyPair = keyPairGen.generateKeyPair();
//            // 私钥
//            RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
//            // 公钥
//            RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
//            String privateKeyStr = base64Encode(privateKey.getEncoded());
//            String publicKeyStr = base64Encode(publicKey.getEncoded());
//            keyMap.put(0,publicKeyStr);
//            keyMap.put(1,privateKeyStr);
//        } catch (NoSuchAlgorithmException e) {
//            e.printStackTrace();
//        }
//        return keyMap;
//    }
//

    /**
     * 公钥加密
     * @param data 需要加密的数据
     * @param key 公钥
     */
    public static String encrypt(String data,String key){
        byte[] decoded = base64Decode(key);
        byte[] result = new byte[]{0};
        try {
            RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance(RSA)
                    .generatePublic(new X509EncodedKeySpec(decoded));
            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE,pubKey);
            result = cipher.doFinal(data.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return base64Encode(result);
    }

    private static byte[] base64Decode(String data) {
        try {
            return Base64.decode(data,Base64.NO_WRAP);
        } catch (Exception e) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                return java.util.Base64.getMimeDecoder().decode(data);
            }
        }
        return null;
    }

    private static String base64Encode(byte[] data) {
        try {
            return Base64.encodeToString(data,Base64.NO_WRAP);
        } catch (Exception e) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                return java.util.Base64.getEncoder().encodeToString(data);
            }
        }
        return null;
    }
}
